package org.zn.etl.datasource;

import java.time.Duration;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.stereotype.Component;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import io.micrometer.core.instrument.Clock;
import io.micrometer.core.instrument.logging.LoggingMeterRegistry;
import io.micrometer.core.instrument.logging.LoggingRegistryConfig;

@Component("JdbcDataSourceFactory")
public class JdbcDataSourceFactory extends DataSourceFactory{

	 public DataSource getDataSource(String  keyName,Map<String, String> dataSourceConfig) throws Exception{
		 
		 DataSource ds=context.get(keyName);
		 if(ds==null) {
		 HikariConfig config=new HikariConfig();

		 config.setPoolName(keyName);
		 config.setJdbcUrl(dataSourceConfig.get(DataSourceKey.JDBC_URL));
		 config.setPassword(dataSourceConfig.get(DataSourceKey.PASSWORD));
		 config.setUsername(dataSourceConfig.get(DataSourceKey.USERNAME));
		 config.setMinimumIdle(Integer.valueOf(dataSourceConfig.get(DataSourceKey.MIN_SIZE))   );
		 config.setDriverClassName(dataSourceConfig.get(DataSourceKey.DRIVER_CLASS));
		 config.setMaximumPoolSize(Integer.valueOf(dataSourceConfig.get(DataSourceKey.MAX_POOL_SIZE)));
		 config.setAutoCommit(  dataSourceConfig.get(DataSourceKey.AUTO_COMMIT)!=null? Boolean.valueOf(dataSourceConfig.get(DataSourceKey.AUTO_COMMIT)) :true);
		 
		 HikariDataSource  hkds=new HikariDataSource(config);
		 
		 //hkds.setMetricRegistry(meterRegistry(keyName));
		 ds=hkds;
		  
		 context.put(keyName, hkds);
		 
		 }
		 
		return ds;
		 
	 }

	 
	 
	 private  LoggingMeterRegistry meterRegistry(String keyName) {
	 
	 LoggingMeterRegistry loggingMeterRegistry = new LoggingMeterRegistry(new LoggingRegistryConfig() {
         @Override
         public String get(String key) {
             return keyName+".meter";
         }
         @Override
         public Duration step() {
             return Duration.ofSeconds(30);
         }
         
         @Override
         public Duration connectTimeout() {
         	// TODO Auto-generated method stub
         	return Duration.ofMinutes(3l);
         }
         
         @Override
         public Duration readTimeout() {
         	// TODO Auto-generated method stub
         	return Duration.ofSeconds(60L);
         }
         
         @Override
         public int batchSize() {
         	// TODO Auto-generated method stub
         	return  1000;
         }
         @Override
         public int numThreads() {
         	// TODO Auto-generated method stub
         	return 4;
         }
         @Override
         public boolean logInactive() {
         	// TODO Auto-generated method stub
         	return true;
         }
         
         @Override
         public boolean enabled() {
         	// TODO Auto-generated method stub
         	return true;
         }
	  
	  },Clock.SYSTEM);
	return loggingMeterRegistry;
	 
	 
	 }

}
